package com.haoze.common.utils;

import com.haoze.common.utils.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeBuildUtilEmrCatalog {

    public static <T> Tree<T> build(List<Tree<T>> nodes, String parentId) {

        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();

        for (Tree<T> children : nodes) {

            String pid = children.getParentId();
            if (pid == null || parentId.equals(pid)) {
                topNodes.add(children);
                continue;
            }

            for (Tree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    children.setHasParent(true);
                    parent.setChildren(true);
                    continue;
                }
            }
        }

        Tree<T> root = new Tree();
        if (topNodes.size() == 1) {
            root = topNodes.get(0);
        }
        return root;
    }
}
